﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLibrary;

namespace ObTookit.Auto
{
    public class JsCoder : BaseCoder
    {
        public string CreateCode()
        {
            FieldObject pkFO = GetIdObject();
            string text = ReadTemplate(Template);
            text = text.Replace("[#AUTHOR#]", Author);
            text = text.Replace("[#CREATED#]", CreateDate);

            text = text.Replace("[#ColumnsFormAdd#]", CreateFormAdd());
            text = text.Replace("[#ColumnsFormSubmit#]", CreateFormSubmit());
            text = text.Replace("[#ColumnsObj#]", CreateO());
            text = text.Replace("[#ClsName#]", AutoObj.ClsName);
            text = text.Replace("[#sClsName#]",StringUtil.FirstChar(AutoObj.ClsName, "_", false));
            text = text.Replace("[#IdAlias#]", pkFO.Alias);
            return text;
        }

        private string CreateFormAdd()
        {
            StringBuilder colObj = new StringBuilder();
            foreach (FieldObject fo in FieldObjs)
            {
                if(!fo.PrimaryKey) 
                {
                    colObj.Append(CodeArgs.TAB3 + fo.Alias 
                    + ": $('#" + fo.Alias + "').val();" + CodeArgs.RN);
                }
            }
            return colObj.ToString();
        }

        private string CreateFormSubmit()
        {
            StringBuilder colObj = new StringBuilder();
            foreach (FieldObject fo in FieldObjs)
            {
                if (!fo.PrimaryKey)
                {
                    colObj.Append(CodeArgs.TAB3 + fo.Alias
                    + " = $('#" + fo.Alias + "').val();" + CodeArgs.RN);
                }
            }
            return colObj.ToString();
        }

        private string CreateO() 
        {
            StringBuilder colObj = new StringBuilder();
            foreach (FieldObject fo in FieldObjs)
            {
                if(!fo.PrimaryKey) 
                {
                    colObj.Append(CodeArgs.TAB2 + "o." + fo.Alias 
                    + " = " + fo.Alias + ";" + CodeArgs.RN);
                }
            }
            return colObj.ToString();
        }
    }
}
